import { defineStore } from 'pinia'
import { ref } from 'vue'
import { IRecord, getRecordsByUserIDAPI, getRecordByIDAPI, deleteRecordByIDAPI } from '@/service/record/record.ts'

export const useRecordStore = defineStore(
  'record',
  ()=>{
    const records = ref<IRecord[]>([]);
    
    const currentRecord = ref<IRecord | null>(null);
    
    // 修改1: 添加获取最新记录的方法
    const getLatestRecord = () => {
      if (records.value.length > 0) {
        return records.value[0];
      }
      return null;
    }
    
    // 修改2: 添加添加新记录的方法
    const addRecord = (record: IRecord) => {
      // 确保记录不存在才添加
      if (!records.value.some(r => r.id === record.id)) {
        // 将新记录添加到数组开头（最新记录在前）
        records.value.unshift(record);
        // 自动设置为当前记录
        currentRecord.value = record;
      }
    }
    
    // 修改3: 优化getRecords方法，确保记录按时间排序
    const getRecords = async (user_id:number) => {
      try {
        const response = await getRecordsByUserIDAPI(user_id);
        // 按创建时间降序排序（最新的在前）
        records.value = response.sort((a, b) => 
          new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
        );
        
        // 如果没有当前记录，设置第一条为当前记录
        if (!currentRecord.value && records.value.length > 0) {
          currentRecord.value = records.value[0];
        }
      } catch (error) {
        console.error('Error fetching Records:', error);
      }
    };
    
    // 修改4: 优化setCurrentRecord方法
    const setCurrentRecord = (record: IRecord) => {
      currentRecord.value = record;
    }
    
    // 修改5: 优化getCurrentRecord方法
    const getCurrentRecord = async (record_id: number) => {
      try {
        // 先在本地查找
        const localRecord = records.value.find(r => r.id === record_id);
        if (localRecord) {
          currentRecord.value = localRecord;
          return;
        }
        
        // 本地没有则从API获取
        const response = await getRecordByIDAPI(record_id);
        currentRecord.value = response;
        
        // 添加到记录列表
        if (response && !records.value.some(r => r.id === response.id)) {
          records.value.unshift(response);
        }
      } catch (error) {
        console.error('Error fetching Record:', error);
      }
    }
    
    const deleteRecord = async (record_id:number) => {
      try {
        await deleteRecordByIDAPI(record_id);
        // 从本地记录中删除
        records.value = records.value.filter(r => r.id !== record_id);
        // 如果删除的是当前记录，清除当前记录
        if (currentRecord.value?.id === record_id) {
          currentRecord.value = null;
        }
      } catch (error) {
        console.error('Error deleting Record:', error);
      }
    }
    
    return {
      records,
      currentRecord,
      getRecords,
      setCurrentRecord,
      getCurrentRecord,
      deleteRecord,
      addRecord,       // 新增
      getLatestRecord  // 新增
    };
  }
)